<template>
  <div class="user-manage">
    <el-form class="query-form"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      size="small"
      label-width="">
        <el-form-item label="注册所属项目" prop="reg_app_id">
          <el-select v-model="queryParams.reg_app_id" placeholder="请选择" @change="handleQuery">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in permission_projectList" :key="item.dictValue"
              :label="item.name"
              :value="item.app_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册渠道" prop="channel_id">
          <el-select v-model="queryParams.channel_id"
            filterable
            placeholder="请选择"
            @change="handleQuery">
            <el-option
              label="全部"
              :value="null" />
            <el-option v-for="item in channelOptions"
              :key="item.channel_id"
              :label="`${item.name}(${item.channel_id})`"
              :value="item.channel_id+''" />
          </el-select>
        </el-form-item>
        <el-form-item label="终端" prop="terminal" class="small-query">
          <el-select v-model="queryParams.terminal" placeholder="请选择" @change="handleQuery">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in terminalOptions" :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="reg_country">
          <el-select v-model="queryParams.reg_country" filterable placeholder="请选择" @change="handleQuery">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in country" :key="item.cnName"
              :label="item.cnName"
              :value="item.cnName" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册方式" prop="reg_type" class="small-query">
          <el-select v-model="queryParams.reg_type" filterable placeholder="请选择" @change="handleQuery">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in userTypeOptions" :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item class="big-query" label="注册时间" prop="createdDateRange">
          <el-date-picker v-model="queryParams.createdDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="注册来源" prop="source_type" class="small-query">
          <el-select v-model="queryParams.source_type" filterable placeholder="请选择" @change="handleQuery">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in regSourceOptions" :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否会员"
          class="small-query"
          prop="is_member">
          <el-select v-model="queryParams.is_member"
            placeholder="请选择"
            @change="handleQuery">
            <el-option
              label="全部"
              :value="10" />
            <el-option
              label="是"
              :value="1" />
            <el-option
              label="否"
              :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态"
          class="small-query"
          prop="status">
          <el-select v-model="queryParams.status"
            placeholder="请选择" @change="handleQuery">
            <el-option v-for="item in userStatus"
              :key="item.id"
              :label="item.desc"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item class="big-query" label="首次消费时间">
          <el-date-picker v-model="firstChargeDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="big-query" label="最近消费时间">
          <el-date-picker v-model="lastLoginDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单总数">
          <el-input-number v-model="numberRange.total_buy_times_begin"
            placeholder="最小值"
            size="small"
            style="width: 76px"/>
          -
          <el-input-number v-model="numberRange.total_buy_times_end"
            placeholder="最大值"
            size="small"
            style="width: 76px"/>
        </el-form-item>
        <el-form-item label="消费总金额">
          <el-input-number v-model="numberRange.total_pay_money_begin"
            placeholder="最小值"
            size="small"
            style="width: 76px"/>
          -
          <el-input-number v-model="numberRange.total_pay_money_end"
            placeholder="最大值"
            size="small"
            style="width: 76px"/>
        </el-form-item>
        <!-- <el-form-item label="剩余使用天数"
          class="small-query"
          prop="status">
          <el-select v-model="remainingDays.package"
            placeholder="请选择权益包" @change="handleQuery"
            :style="{ marginRight: '5px' }">
            <el-option v-for="item in packageOptions"
              :key="item.id"
              :label="item.desc"
              :value="item.id" />
          </el-select>
          <el-input-number v-model="remainingDays.remaining_day_begin"
            placeholder="最小值"
            size="small"
            style="width: 76px"/>
          -
          <el-input-number v-model="remainingDays.remaining_day_end"
            placeholder="最大值"
            size="small"
            style="width: 76px"/>
        </el-form-item>
        <el-form-item label="使用截止时间"
          class="small-query"
          prop="status">
          <el-select v-model="useDeadline.package"
            placeholder="请选择权益包" @change="handleQuery"
            :style="{ marginRight: '5px' }">
            <el-option v-for="item in packageOptions"
              :key="item.id"
              :label="item.desc"
              :value="item.id" />
          </el-select>
          <el-date-picker v-model="useDeadline.useDeadlineDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item class="big-query" label="关键词"
          prop="search_kw">
          <el-input v-model="queryParams.search_kw"
            placeholder="输入用户ID、用户昵称、手机号"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            @clear="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
            size="small"
            @click="handleQuery">搜索</el-button>
          <el-button size="small"
            @click="resetQuery">重置</el-button>
          <el-button
            size="small"
            type="success"
            :loading="exportLoading"
            @click="exportExcel">导出全部</el-button>
        </el-form-item>
    </el-form>
    <div class="text-right">
      <el-popover
        placement="bottom-end"
        popper-class="table-check_popover"
        width="560"
        trigger="click">
        <div>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">字段选择</el-checkbox>
          <hr/>
          <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
            <div>
              <span class="table-check_label">用户信息：</span>
              <el-checkbox label="reg_type">注册方式</el-checkbox>
              <el-checkbox label="mobile">注册账号</el-checkbox>
              <el-checkbox label="channel">注册渠道</el-checkbox>
              <el-checkbox label="terminal">终端</el-checkbox>
              <el-checkbox label="reg_country">区域</el-checkbox>
            </div>
            <div class="mt10">
              <span class="table-check_label">用户信息：</span>
              <el-checkbox label="created_at">注册时间</el-checkbox>
              <el-checkbox label="source_type">注册来源</el-checkbox>
            </div>
            <div class="mt10">
              <span class="table-check_label">交易统计：</span>
              <el-checkbox label="is_member">是否会员</el-checkbox>
              <el-checkbox label="last_charge_at">最近消费时间</el-checkbox>
              <el-checkbox label="first_charge_at">首次消费时间</el-checkbox>
              <el-checkbox label="total_member_times">订单总数</el-checkbox>
              <el-checkbox label="total_pay_money">消费总金额</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <el-button type="text" slot="reference">字段选择<i class="el-icon-arrow-down"></i></el-button>
      </el-popover>
    </div>
    <el-table v-loading="loading" :data="userList" @sort-change="onSortChange" style="width:100%">
      <el-table-column label="用户ID" min-width="100" prop="user_id" />
      <el-table-column label="用户昵称" min-width="110" prop="nick_name" />
      <el-table-column label="注册渠道" width="160" prop="channel_id" v-if="checkList.includes('channel')">
        <template #default="{ row }">
          <span>{{ row.channel_id |  translateToName(channelOptions, 'channel_id', 'name')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="终端"
        v-if="checkList.includes('terminal')"
        width="100">
        <template slot-scope="scope">
          <span>{{ terminalFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="区域" min-width="120" prop="reg_country" v-if="checkList.includes('reg_country')"/>
      <el-table-column label="注册方式" min-width="120" prop="reg_type" v-if="checkList.includes('reg_type')">
        <template slot-scope="scope">
          <span>{{ userTypeFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册来源" min-width="120" prop="source_type" v-if="checkList.includes('source_type')">
        <template slot-scope="scope">
          <span>{{ sourceTypeFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" min-width="120" prop="created_at" v-if="checkList.includes('created_at')"/>
      <el-table-column label="注册账号" min-width="120" prop="reg_account" v-if="checkList.includes('mobile')"/>
      <el-table-column label="注册所属项目"
        width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.reg_app_id|translateToName(permission_projectList,'app_id','name') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否会员"
        v-if="checkList.includes('is_member')"
        min-width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_member? 'success' : 'danger'" disable-transitions>{{ scope.row.is_member ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="首次消费时间"
         min-width="160"
        prop="first_charge_at"
        v-if="checkList.includes('first_charge_at')"
        sortable="custom"
        :show-overflow-tooltip="true" />
      <el-table-column label="最近消费时间"
         min-width="160"
        prop="last_charge_at"
        v-if="checkList.includes('last_charge_at')"
        sortable="custom"
        :show-overflow-tooltip="true" />
      <el-table-column label="订单总数"
         min-width="160"
        prop="total_member_times"
        v-if="checkList.includes('total_member_times')"
        sortable="custom"
        :show-overflow-tooltip="true" />
      <el-table-column label="消费总金额" min-width="120" prop="total_pay_money" sortable="custom" v-if="checkList.includes('total_pay_money')">
        <template #default={row}>
          {{ row.total_pay_money | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="账号状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status===1?'success':scope.row.status===5?'danger':'info'" disable-transitions>{{ scope.row.status|filterStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="small" type="text" @click="updateStatus(scope.row)">{{scope.row.status===5?'解冻':'冻结'}}</el-button>
          <el-button size="small" type="text" @click="handleDevice(scope.row)">设备详情</el-button>
          <el-popover placement="bottom" width="60" trigger="hover" :offset="-6" style="margin-left: 10px;">
            <p><el-button style="display: block; width: 100%;" size="small" type="text" @click="openPrivderCoupon(scope.row)">优惠券</el-button></p>
            <el-button size="small" type="text" slot="reference">发放</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" layout="total,slot,sizes,prev,pager,next,jumper" :page.sync="queryParams.page" :limit.sync="queryParams.page_size" @pagination="getList">
      <span class="span-amount">共 {{amount|formatMoney}} 元</span>
    </pagination>
    <!-- 用户详情 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" :close-on-click-modal="false" top="5vh">
      <userDetail :userInfo="userInfo" :channelOptions="channelOptions"/>
    </el-dialog>
    <user-device ref="userDeivceRef"/>
    <provider-coupon ref="providerCouponRef"/>
  </div>
</template>

<script>
import Axios from 'axios'
import { mapGetters } from 'vuex'
import country from '@/json/country.json'
import { listUser, getUser, freezeUser, createExportUserTask, queryExportUserTask } from '@/api/user/user'
import { getChannelByAppId } from '@/api/system/channel'
import { parseTime, downloadExportUrl } from '@/utils'
import storage from '@/utils/storage'
import userDetail from '@/views/user/components/user-detail.vue'
import userDevice from '@/views/user/components/user-device.vue'
import ProviderCoupon from './components/provider-coupon.vue'

const tableOpt = ['reg_type', 'mobile', 'channel', 'terminal', 'reg_country', 'created_at', 'is_member', 'first_charge_at', 'total_pay_money', 'last_charge_at', 'total_member_times', 'source_type']
export default {
  name: 'UserList',
  components: {
    userDetail,
    userDevice,
    ProviderCoupon
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 总金额
      amount: 0,
      // 权益表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      userInfo: {},
      userStatus: [
        { id: 10, desc: '全部' },
        { id: 1, desc: '正常' },
        { id: 5, desc: '已冻结' },
        { id: 9, desc: '已注销' }
      ],
      // 渠道选项
      channelOptions: [],
      terminalOptions: [],
      userTypeOptions: [],
      regSourceOptions: [],
      // 权益包选项
      packageOptions: [],
      // 剩余使用天数
      // remainingDays: {
      //   package: '',
      //   remaining_day_begin: undefined,
      //   remaining_day_end: undefined
      // },
      // 使用截止时间
      // useDeadline: {
      //   package: '',
      //   useDeadlineDateRange: null
      // },
      // 查询条件 - 最近登录时间
      lastLoginDateRange: null,
      // 首次消费时间
      firstChargeDateRange: null,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        channel_id: null,
        reg_type: '',
        terminal: null,
        reg_country: null,
        is_member: 10,
        status: 1,
        trial_status: null,
        login_app_id: null,
        reg_app_id: null,
        // 查询条件 - 首次充值会员时间
        createdDateRange: null,
        firstChargeDateRange: null,
        search_kw: null,
        sort_field: '',
        sort_method: '',
        source_type: ''
      },
      country: country,
      checkAll: false,
      isIndeterminate: false,
      checkList: [],
      numberRange: {
        total_buy_times_begin: undefined,
        total_buy_times_end: undefined,
        total_pay_money_begin: undefined,
        total_pay_money_end: undefined
      },
      exportLoading: false
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  filters: {
    filterStatus (val) {
      const obj = {
        1: '正常',
        5: '已冻结',
        9: '已注销'
      }
      return obj[val] || '其他'
    }
  },
  created () {
    const now = parseTime(new Date(), '{y}-{m}-{d}')
    const list = this.permission_projectList.map(item => item.app_id)
    this.queryParams.createdDateRange = [now, now]
    this.checkList = storage.get('userTable') || [...tableOpt]
    this.handleCheckedChange(this.checkList)
    Axios.all([this.getListApi(), getChannelByAppId({ app_ids: list.join(',') })]).then(Axios.spread((res1, res2) => {
      this.channelOptions = res2.data.list
      this.userList = res1
    }))
    this.getDicts('terminal').then(res => {
      this.terminalOptions = (res.data || []).map(item => {
        item.dictValue = parseInt(item.dictValue) || 0
        return item
      })
    })
    this.getDicts('user_account_type').then(res => {
      this.userTypeOptions = res.data || []
    })
    this.getDicts('reg_source').then(res => {
      this.regSourceOptions = res.data || []
    })
  },
  methods: {
    mergeQueryParams () {
      let params = this.deepClone(this.queryParams)
      const lastLoginDate = this.addDateRange(this.lastLoginDateRange, 'last_charge_begin', 'last_charge_end')
      const firstChargeDate = this.addDateRange(this.firstChargeDateRange, 'first_charge_begin', 'first_charge_end')
      const createdDate = this.addDateRange(this.queryParams.createdDateRange, 'created_at_begin', 'created_at_end')
      const buyTime = { total_buy_times_begin: this.numberRange.total_buy_times_begin, total_buy_times_end: this.numberRange.total_buy_times_end }
      const payMoney = { total_pay_money_begin: this.numberRange.total_pay_money_begin * 100, total_pay_money_end: this.numberRange.total_pay_money_end * 100 }

      Object.assign(params, lastLoginDate, firstChargeDate, createdDate, buyTime, payMoney)

      return params
    },
    queryExportTask (task_id, func) {
      queryExportUserTask({ task_id })
        .then(response => {
          if (response.data?.status === 'finished') {
            downloadExportUrl(response.data.file_url)
            typeof func === 'function' && func(true)
          } else {
            setTimeout(() => {
              this.queryExportTask(task_id, func)
            }, 1000)
          }
        })
        .catch(() => {
          typeof func === 'function' && func(false)
        })
    },
    exportExcel () {
      this.exportLoading = true
      const queryParams = this.mergeQueryParams()
      const params = Object.assign({}, queryParams)
      delete params.page
      delete params.page_size

      console.log(params)
      createExportUserTask({ filter: params })
        .then(response => {
          const { task_id } = response.data || {}
          if (task_id) {
            this.queryExportTask(task_id, () => {
              this.exportLoading = false
            })
          } else {
            this.$message.error('导出订单任务创建失败')
            this.exportLoading = false
          }
        })
        .catch(e => {
          this.exportLoading = false
        })
    },
    handleCheckAllChange (val) {
      this.checkList = val ? [...tableOpt] : []
      this.isIndeterminate = false
      storage.set('userTable', this.checkList)
    },
    handleCheckedChange (value) {
      const checkedCount = value.length
      const count = tableOpt.length
      this.checkAll = checkedCount === count
      this.isIndeterminate = checkedCount > 0 && checkedCount < count
      storage.set('userTable', value)
    },
    terminalFormat (row, column) {
      return this.selectDictLabel(this.terminalOptions, row.terminal)
    },
    userTypeFormat (row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.reg_type)
    },
    sourceTypeFormat (row) {
      const sourceType = row.source_type
      if (!sourceType) {
        return '-'
      }

      return this.regSourceOptions.find(i => i.dictValue === sourceType)?.dictLabel || '-'
    },
    getListApi () {
      const params = this.mergeQueryParams()
      this.loading = true
      return new Promise((resolve, reject) => {
        listUser(params).then(response => {
          const data = response.data || {}
          resolve(data.list)
          this.amount = data.amount
          this.total = data.count || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    /** 查询用户列表 */
    getList () {
      this.getListApi().then(res => {
        this.userList = res
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      // if (this.useDeadline.useDeadlineDateRange && !this.useDeadline.package) {
      //   this.$message({
      //     type: 'error',
      //     message: '请检查权益包输入'
      //   })
      //   return
      // }

      // if ((this.remainingDays.remaining_day_begin || this.remainingDays.remaining_day_end) && !this.remainingDays.package) {
      //   this.$message({
      //     type: 'error',
      //     message: '请检查权益包输入'
      //   })
      //   return
      // }

      const isPayMoneyValid = this.validNumberRangeInput(this.numberRange, 'total_pay_money_begin', 'total_pay_money_end')
      const isBuyTimesValid = this.validNumberRangeInput(this.numberRange, 'total_buy_times_begin', 'total_buy_times_end')
      if (!isPayMoneyValid || !isBuyTimesValid) {
        this.msgError('请检查数字区间输入')
        return
      }

      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.lastLoginDateRange = null
      this.firstChargeDateRange = null
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })

      // Object.keys(this.remainingDays).forEach(key => {
      //   this.remainingDays[key] = undefined
      // })

      // Object.keys(this.useDeadline).forEach(key => {
      //   this.useDeadline[key] = undefined
      // })
      this.resetForm('queryForm')
      this.handleQuery()
    },
    onSortChange ({ prop, order }) {
      this.queryParams.sort_field = order ? prop : null
      this.queryParams.sort_method = order === 'descending' ? 'desc' : 'asc'
      this.getList()
    },
    /** 冻结/解冻/注销按钮操作 */
    updateStatus (row) {
      const lastStatus = row.status === 1 ? 5 : 1

      const tips = lastStatus === 1 ? '解冻' : '冻结'
      this.$confirm(`确定${tips}该账号吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        freezeUser(row.auth_id, lastStatus).then(() => {
          this.getList()
          this.msgSuccess(`已成功${tips}该账号`)
        })
      })
    },
    /** 查看详情 */
    handleDetail (row) {
      this.loading = true
      getUser(row.auth_id).then(response => {
        const data = response.data
        data.reg_types = this.userTypeFormat(data)
        this.userInfo = data
        this.title = '用户详情'
        this.open = true
      }).finally(() => {
        this.loading = false
      })
    },
    handleDevice (row) {
      console.log('this is open device', row)
      this.$refs.userDeivceRef.open(row)
    },
    openPrivderCoupon  (item) {
      this.$refs.providerCouponRef.open(item)
    }
  }
}
</script>
